<?php

/**
 * Image Controller
 */
class AW_Imagetest_ImageController extends Mage_Core_Controller_Front_Action
{
 /** 
     * Getting new image status config path
     */
    const GET_STATUS_PATH = 'imagetest/general/new_image_status';
    
    /**
     * Response for Ajax Request
     * @param array $result
     */
    protected function _ajaxResponse($result = array())
    {
        $this->getResponse()->setBody(Zend_Json::encode($result));
    }

    /**
     * Rate action
     */
    public function rateAction()
    {
        if ( ($id = $this->getRequest()->getParam('id')) && ($rate = $this->getRequest()->getParam('rate')) ){
            if ( !(($rate >= 1) && ($rate <= 5)) ){
                $this->_ajaxResponse(array('error'=>'Wrong rate param'));
                return;
            }

            if ( Mage::helper('imagetest')->confRatingStatus() < AW_Imagetest_Model_System_Config_Source_Rating::STATUS_DISPLAY_AND_RATE ){
                $this->_ajaxResponse(array('error'=>'Rating disallowed'));
                return;
            }

            $image = Mage::getModel('imagetest/image')->load($id);
            if ($image->getImageId()){

                if (Mage::helper('imagetest')->isRateRegistered($id)){
                    $this->_ajaxResponse(array('error'=>'You already rate this image'));
                    return;
                }

                $votes = ($image->getVotes() >= 0) ? $image->getVotes() : 0;
                $oldRate = $image->getRate();
                
                $sum = $votes * $oldRate + ($rate * 20);
                $votes++;
                $rate = round($sum / $votes);

                $rate = min(100, $rate);
                $rate = max(0, $rate);


                $image->setVotes($votes);
                $image->setRate($rate);
                $image->save();
                Mage::helper('imagetest')->registerRate($id);
                $this->_ajaxResponse(array('newrate'=>$rate));
                return;
            }
            $this->_ajaxResponse(array('error'=>'Image not found'));
        } else {
            $this->_ajaxResponse(array('error'=>'Image id missed'));
        }                        
    }
/**
     * Get customer image
     */
    public function postAction()
    {
        $data = new Varien_Object($this->getRequest()->getPost());
        $file = new Varien_Object(isset($_FILES['image_file']) ? $_FILES['image_file'] : array());

        if (!Mage::helper('imagetest')->canUpload()){
            Mage::helper('imagetest')->addCustomerError(Mage::helper('imagetest')->__('You can not upload image'));
            $this->_removeTempFile($file->getTmpName());
            $this->_redirectReferer();
            return;
        }

        if ($file->getError() && $data->getImageType() == 'file'){
            Mage::helper('imagetest')->addCustomerError('Image uploaded error');
            return;
        }

        $helper = Mage::helper('imagetest');

        if (true){
            # Clean key for next post
//            $helper->setValue('youtube_secret_key', null);

            $image = Mage::getModel('imagetest/image');

            # Set up basical info
            $image->setTitle(htmlspecialchars($data->getTitle()));
            $image->setComment($data->getComment());
            $image->setProductId($data->getProductId());
            $image->setAuthorName(htmlspecialchars($data->getAuthorName()));
            $image->setAuthorEmail($data->getAuthorEmail());
            //$image->setApiCode('youtube');
            $image->setStore(Mage::app()->getStore()->getId());
            $image->setState(AW_Imagetest_Model_Image::IMAGE_STATE_NOPREVIEW);

            # Set up access info
            if (Mage::getStoreConfig(self::GET_STATUS_PATH)){
                $image->setStatus(AW_Imagetest_Model_Image::IMAGE_STATUS_ENABLED);
            } else {
                $image->setStatus(AW_Imagetest_Model_Image::IMAGE_STATUS_PENDING);
            }            
           
            try {
               if($_FILES['image_file']) {
                    if($_FILES['image_file']['size']>3*1000*1000){
                        Mage::helper('imagetest')->addCustomerError('Image file is large 3MB.'); 
                        $this->_redirectReferer();
                    }
                    $uploader = new Mage_Core_Model_File_Uploader('image_file');
                    $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png','bmp'));
                    $uploader->setAllowRenameFiles(true);
                    $uploader->setFilesDispersion(true);
                    $result = $uploader->save( Mage::getBaseDir('media') . DS . 'imagetestimonial'.DS );
                    $image->setThumbnail('imagetestimonial'.$result['file']); 
                }
                
               
                $date = new Zend_Date();
                $image->setCreatedAt($date->toString('YYYY-MM-dd HH:mm'));

                $image->save();

                if (Mage::getStoreConfig(self::GET_STATUS_PATH)){
                    if ($data->getImageType() == 'link'){
                        Mage::helper('imagetest')->addCustomerSuccess('Image uploaded successfully');
                    } elseif($data->getImageType() == 'file') {
                        Mage::helper('imagetest')->addCustomerSuccess('Waiting for processing');

                        $image->setStatus(AW_Imagetest_Model_Image::IMAGE_STATUS_PROCESSING);
                        $image->save();
                    }
                } else {
                    Mage::helper('imagetest')->addCustomerSuccess('Image has been accepted for moderation');
                }

            } catch (Exception $e) {
                Mage::helper('imagetest')->addCustomerError($e->getMessage());
            }

            $this->_redirectReferer();

            
        } else {
            $this->_redirectReferer();
        }
    }
    
    public function viewAction(){
        $imageId  = (int) $this->getRequest()->getParam('id');
        $productId  = (int) $this->getRequest()->getParam('productid');
        Mage::register('current_image_id', $imageId);
        if (is_numeric($productId)) {
            $product = Mage::getModel('catalog/product')->load($productId);
            Mage::register('current_product', $product);
            Mage::register('product', $product);
        }
        if(!isset($product) || !$product->getId()){
           Mage::getSingleton('core/session')->addError('Product not found.');
           $this->_redirectReferer(); 
        } 
        $this->loadLayout();
        $this->renderLayout(); 
    
    }
}
